package com.sinodata.bsm.cicp.collector.mysql;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class InnodbCollector extends AbstractJDBCCollector {
    private final Logger logger = Logger.getLogger(InnodbCollector.class);
    private final Map<String, String> dbKeyMap = new HashMap<String, String>();

    public InnodbCollector() {
        MySQLUtil.initDbKeyMap(getDbServKeys(), getPropMeta(), dbKeyMap);
    }

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        Map<String, String> dbMap = collectStatusFromDb(ip);
        List<ResPropertyValue> values = MySQLUtil.createPropValues(getDbKeyMap(), getPropMeta(), dbMap);
        dbMap.clear();
        return values;
    }

    public Map<String, String> collectStatusFromDb(String ip) throws CollectorException {
        String dbtype = getParamMap().get("DBType");
        String dbname = getParamMap().get("DBName");

        ResultSet rsStatus = null;
        Map<String, String> dbMap = new HashMap<String, String>();
        try {
            rsStatus = this.getCachedResultSet(dbtype, ip, dbname, MySQLContants.STATUS);
            while (rsStatus.next()) {
                dbMap.put(rsStatus.getString(1).toLowerCase(), rsStatus.getString(2) == null ? "" : rsStatus.getString(2).trim().toLowerCase());
            }
        } catch (Exception ex) {
            logger.error("collect mysql(" + ip + ") information error", ex);
            throw new CollectorException("collect mysql(" + ip + ") information error", ex);
        }
        return dbMap;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "DBType", "DBName" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "InnodbPageSize", "InnodbCachePoolSize", "FreeInnodCache", "ReadDataTimes", "TotalReadDataSize", "WriteDataTimes", "TotalWriteDataSize", "WriteLogTimes", "TotalWriteLogSize" };
    }

    private String[] getDbServKeys() {
        return new String[] { "innodb_page_size", "innodb_buffer_pool_pages_total", "innodb_buffer_pool_pages_free", "innodb_data_reads", "innodb_data_read", "innodb_data_writes", "innodb_data_written", "innodb_log_writes", "innodb_os_log_written" };
    }

    public Map<String, String> getDbKeyMap() {
        return dbKeyMap;
    }

    public void setDbKeyMap(String propMeta, String dbKey) {
        this.dbKeyMap.put(propMeta, dbKey);
    }
}
